package com.yuxl.common.auth.service;

import com.yuxl.common.auth.entity.AuthRole;
import com.yuxl.common.auth.entity.AuthUser;
import com.yuxl.common.auth.entity.AuthUserRole;
import com.yuxl.common.auth.repository.AuthUserRoleRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import jakarta.annotation.Resource;
import java.util.List;

/**
 * @author yuxl
 */
@Slf4j
@Service
public class AuthUserRoleService {
    @Resource
    private AuthUserRoleRepository authUserRoleRepository;

    public Flux<AuthRole> findByUserId(Long userId) {
        return authUserRoleRepository.findByUserId(userId);
    }

    public Flux<AuthRole> findByUserIds(List<Long> userIds) {
        return authUserRoleRepository.findByUserIds(userIds);
    }

    public Flux<AuthUser> findByRoleMark(String roleMark) {
        return authUserRoleRepository.findByRoleMark(roleMark);
    }
    public Flux<AuthUser> findByRoleMarks(List<String> roleMarks) {
        return authUserRoleRepository.findByRoleMarks(roleMarks);
    }

    public Flux<AuthUserRole> save(Long userId, List<String> roleMarks){
        if (roleMarks == null || roleMarks.isEmpty()) {
            return Flux.empty();
        }
        List<AuthUserRole> list = roleMarks.stream().map(roleMark -> new AuthUserRole().setUserId(userId).setRoleMark(roleMark)).toList();
        return authUserRoleRepository.deleteByUserId(userId)
                .flatMapMany(k->authUserRoleRepository.saveAll(list))
                ;
    }

    public Mono<Long> deleteByUserId(Long userId){
        return authUserRoleRepository.deleteByUserId(userId);
    }

    public Flux<AuthUserRole> save(List<Long> userIds, String roleMark){
        if (userIds == null || userIds.isEmpty()) {
            return Flux.empty();
        }
        List<AuthUserRole> list = userIds.stream().map(userId -> new AuthUserRole().setUserId(userId).setRoleMark(roleMark)).toList();
        return authUserRoleRepository.deleteByRoleMark(roleMark)
                .flatMapMany(k->authUserRoleRepository.saveAll(list));
    }

    public Mono<Long> deleteByRoleMark(String roleMark){
        return authUserRoleRepository.deleteByRoleMark(roleMark);
    }


} 